<template>
	<section>
		<!--工具条，就是高级查询的那个框-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="员工名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getQueryEmployees">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="this.pageInfo.dataList" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" label="序号" width="60">
			</el-table-column>
      <el-table-column prop="username" label="员工账号" width="120">
      </el-table-column>
      <el-table-column prop="password" label="员工密码" width="200">
      </el-table-column>
      <el-table-column prop="email" label="员工邮箱" min-width="120">
      </el-table-column>
      <el-table-column prop="headImage" label="员工头像路径" width="200">
      </el-table-column>
      <el-table-column prop="age" label="员工年龄" width="180">
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门" width="120">
      </el-table-column>
			<el-table-column label="操作" width="250">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<el-button type="warning" size="small" @click="handleRole(scope.$index, scope.row)">绑定角色</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-- 批量删除和分页 -->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<!--			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="this.query.pageSize" :total="this.pageInfo.total" style="float:right;">
			</el-pagination>-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="this.query.currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="10"
          style="float:right"
          layout="total,sizes, prev, pager, next"
          :total="this.pageInfo.total">
      </el-pagination>
		</el-col>

		<!--新增/修改界面-->
		<el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="员工账号" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-select v-model="saveForm.department" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in department"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
      </el-form-item>
      </el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" >提交</el-button>
			</div>
		</el-dialog>

    <!--    角色弹窗-->
    <el-dialog title="设置角色" :visible.sync="setRoleVisible" :close-on-click-modal="false">
      <el-form :model="role" label-width="80px" ref="saveForm">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div class="checkbox-table" v-for="(r,indexkey) in sysRoles" :key="r.id">
          <template>
            <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                         v-model='role.roleIds' :label="r.id"
                         @change='handleCheck(indexkey)'>
              {{r.name}}
            </el-checkbox>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setRoleVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveRole" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'

	export default {
		data() {
			return {
				query: {  // 定义高级查询的 属性，也是要通过请求带给后端的
					keyword: '',
          currentPage:1,
          pageSize:10
				},
        pageInfo:{
          dataList: [],
          total: 0,
        },
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				saveFormVisible: false,//新增界面是否显示
				saveFormRules: {
					username: [
						{ required: true, message: '请输入账号', trigger: 'blur' }
					],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          department: [
            { required: true, message: '请输入所属部门', trigger: 'blur' }
          ]
				},
				//新增界面数据
				saveForm: {
          id: null,
          username: " ",
          password: "",
          email:"",
          age:null,
          department:{
            id:null
          }
        },
        department:[],

        // 角色模块
        setRoleVisible:false,
        role:{  // 定义角色
          id:null,
          roleIds:[]    // 前端显示的框框
        },
        isIndeterminate:false,  //复选框，不确定状态的，是一个横杠
        checkAll:false,   // 表示全选框 是否为全选状态
        saveLoading:false,
        allRoleIds:[],  // 前端 role 模块中所有的 id 集合
        sysRoles:[]      // 从后台获取到的角色列表，相当于权限树
			}
		},

		methods: {
      // 提交绑定的角色
      saveRole(){
        this.$http.post("/employee/role",this.role)
            .then(result => {
              result = result.data;
              if(result.success){
                // this.role.roleIds = result.ajaxObj;
                this.$message({ message: "提交成功",type: 'success'});
              }else{
                this.$message({ message: result.msg,type: 'error'});
              }
              this.setRoleVisible=false
            })
            .catch(result => {
              this.$message({ message: '系统错误',type: 'error'});
              this.setRoleVisible=false
            })
      },
      // 从后台获取角色数组,allRoleIds 保存了所有的 Id
      getSysRoles(){
        this.$http.get("/role")
            .then(result=>{
              result=result.data;
              if(result.success){
                this.listLoading = false;
                this.sysRoles=result.ajaxObj;
                console.log("这是 getRoles 中的 sysRoles："+this.sysRoles)
                for(let i=0;i<this.sysRoles.length;i++){
                  let p = this.sysRoles[i].id;
                  this.allRoleIds.push(p);
                }
              }
            })
            .catch(result=>{
              this.$message({message: '网络异常',type: 'error'});
            })
      },

      // 绑定角色 的按钮
      handleRole(index,row){
        this.setRoleVisible=true
        // 角色回显
        this.role.id=row.id
        this.getUserRoleById(this.role.id)
        this.getSysRoles()
      },

      /**
       * 根据用户 id 查询对应的角色 id
       * @param id
       */
      getUserRoleById(id){
        this.$http.get("/employee/role/"+id)
            .then(result => {
              result = result.data;
              if(result.success){
                this.role.roleIds = result.ajaxObj;
                console.log("回显的东西:"+result.ajaxObj)
              }else{
                this.$message({ message: result.msg,type: 'error'});
              }
            })
            .catch(result => {
              this.$message({ message: '系统错误',type: 'error'});
            })
      },

      // 角色模块
      
      // 全选框
      handleCheckAllChange(val){
        this.role.roleIds = val ? this.allRoleIds : [];
        this.isIndeterminate = false;
      },
      
      // 勾选权限的方法
      // 处理选择事件  type 1:一级权限2:二级权限   a：一级权限的索引位置
      handleCheck(a = 0) { // 多选框
        let indexOf = this.role.roleIds.indexOf(this.sysRoles[a].id);
        if (type === 2) { // 二级菜单点击
          let index = 0;  //  点击的某个框
          this.sysRoles[a].children.map(item => {
            // 已选中的权限列表中，是否包含当前一级权限下的某个子权限
            if (this.role.roleIds.indexOf(item.id) > -1) {
              index += 1;
            }
          })
          if (index > 0) {  // 已选中的权限列表中，包含当前一级权限下的某个子权限
            if (indexOf < 0) {  // 已选中的权限列表中，没有当前一级权限，则添加到已选中的权限列表中
              this.role.roleIds.push(this.sysRoles[a].id);
            }
          } else {  // // 已选中的权限列表中，不包含当前一级权限下的某个子权限
            if (indexOf > -1) {// 已选中的权限列表中，有当前一级权限，则删除
              this.role.roleIds.splice(indexOf, 1);
            }
          }
        } else {  // 一级菜单点击
          if (indexOf > -1) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
            this.sysRoles[a].children.map(item => {
              if (this.role.roleIds.findIndex((n) => n == item.id) < 0) {
                this.role.roleIds.push(item.id)
              }
            })
          } else {
            // 已选中的权限中，不包含当前一级权限，则将该一级权限下所有的子权限移除
            this.sysRoles[a].children.map(item => {
              if (this.role.roleIds.findIndex((n) => n == item.id) > -1) {
                this.role.roleIds.splice(this.role.roleIds.findIndex((n) => n == item.id), 1);
              }
            })
          }
        }
        // 获取已选中的长度
        let checkedCount = this.role.roleIds.length;
        // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
        this.checkAll = checkedCount === this.allRoleIds.length;
        // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.allRoleIds.length;
      },
     

      // 获取部门列表
      getDepartments(){
        this.$http.get("/department")
            .then(result=>{
              result=result.data;
              if(result.success){
                this.listLoading = false;
                this.department=result.ajaxObj;
              }else {
              }
            })
            .catch(result=>{
              this.$message({message: '网络异常',type: 'error'});
            })
      },

      // 调整每页数据条数
      handleSizeChange(val){
        this.query.pageSize=val;
        this.getEmployees()
      },
      // 点击查询按钮
      getQueryEmployees(){
        this.query.currentPage=1;
        this.getEmployees()
      },

			handleCurrentChange(val) {
				this.query.currentPage=val;
        this.getEmployees() // getEmployees 方法中的 axios 请求会自己来这里找
			},
			//获取员工列表
			getEmployees(){
				this.listLoading = true;
        // 发请求
        this.$http.put("/employee",this.query)
            .then(result=>{
              result=result.data;
              if(result.success){
                this.$message({message: '查询成功',type: 'success'});
                this.listLoading = false;
                this.dataList =result.ajaxObj.dataList
                this.pageInfo =result.ajaxObj;
              }else {
                this.$message({message: '网络异常，请重新登录...',type: 'error'});
              }
            })
            .catch(result=>{
            })
			},

			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					this.$http.delete("/employee/"+row.id)
              .then((result) => {
                result=result.data;
                if(result.success){
                  this.$message({message: '删除成功',type: 'success'});
                  this.listLoading = false;
                  this.query.currentPage=1;
                  this.getEmployees()
                }else {
                  this.$message({message: '删除失败',type: 'error'});
                }
					}).catch();
				}).catch(() => {

				});
			},

			//显示编辑界面的弹窗
			handleEdit: function (index, row) {
				this.saveFormVisible = true;
        this.getDepartments()
				this.saveForm = Object.assign({}, row);   // 回显
			},

			//显示新增界面的弹窗
			handleAdd: function () {
				this.saveFormVisible = true;
        this.saveForm = {
          id: null,
          username: " ",
          password: "",
          email:"",
          age:null,
          department:{
            id:null
          }
        },
        this.getDepartments()
      },

			//新增的提交按钮，上级员工的级联框取数组的最后一个
			addSubmit: function () {
				this.$refs.saveForm.validate((valid) => {   // valid 就是规则的返回值，规则通过了才会有返回值
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.saveForm);  // JSON 格式的转换
              // 发请求
              this.$http.post("/employee",para)
                  .then((result) => {
                    result=result.data;
                    if(result.success){
                      this.$message({message: '保存成功',type: 'success'});
                      this.addLoading=false
                      this.saveFormVisible=false
                      this.getEmployees()
                    }else {
                      this.$message({message: '保存失败',type: 'error'});
                    }
                  })
                  .catch(result => {
                    this.$message({message: '网络异常，请稍后访问',type: 'danger'});
                    
                  })
						});
					}
				});
			},

			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var roleIds = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
          this.$http.patch("/employee",roleIds)
              .then((result) => {
                result=result.data;
                if(result.success){
                  this.$message({message: '批量删除成功',type: 'success'});
                  this.listLoading = false;
                  this.query.currentPage=1;
                  this.getEmployees()
                }else {
                  this.$message({message: '批量删除失败',type: 'error'});
                }
              })
					    .catch(result => {

				      })
			}).catch(()=>{})
		}
    },


		mounted() {
      this.getEmployees();
    }
	}

</script>

<style scoped>

</style>